#include "ThreadPool.h"
#include <iostream>

using std::cout;
using std::endl;

ThreadPool::ThreadPool(size_t threadNum, size_t queSize)
: _threadNum(threadNum)
, _queSize(queSize)
, _taskQue(_queSize)
, _isExit(false)
{
    
}

void ThreadPool::start()//启动线程池
{
    //创建线程
    for(size_t idx = 0; idx < _threadNum; ++idx)
    {
        _threads.push_back(thread(&ThreadPool::doTask, this));
    }
}

void ThreadPool::stop() //终止线程池
{
    //队列不为空：阻塞主进程
    while(!_taskQue.empty())
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    //线程池退出
    _isExit = true;//此时子线程若等待_notEmpty变量时主线程无法退出

    //唤醒所有线程
    _taskQue.wakeup();//子线程继续执行下次循环发现_isExit为true无法继续执行任务

    //等待线程执行结束,回收线程
    for(auto &thread : _threads)
    {
        thread.join();
    }
}

void ThreadPool::addTask(Task &&taskcb)//添加任务到任务队列
{
    if(taskcb)
    {
        _taskQue.push(std::move(taskcb));
    }
}

Task ThreadPool::getTask()//任务队列中获取任务
{
    return _taskQue.pop();
}

void ThreadPool::doTask()//执行任务
{
    while(!_isExit)
    {
        Task taskcb = getTask();
        if(taskcb)
        {
            //ptask->process();
            taskcb();
        }
        else
        {
            cout << "empty task" << endl;
        }
    }
}
